var GameEngine = function ( timeline ) {

	ASBroadcaster.initialize( this );

	this.timeline = timeline;

	Object.registerClass( "PacMan" , PacMan );
	Object.registerClass( "ghost_red" , Ghost_Red );

	this.prepare();

}

var p = GameEngine.prototype = new Screen();

p.prepare = function () {

	this.mazeContext = Maze.buildAndReturnContext( this.timeline );

	this.pacMan = this.assignPacMan();

	this.Ghost_Red = this.assignGhost ( "ghost_red" , 14 << 3 , 11 << 3  );

	// play IntroSound //

	var scope = this;
	var snd = new Sound ( this.timeline );

	snd.attachSound ( "snd_intro" );

	snd.onSoundComplete = function () {

		scope.start();

		delete snd;

	}

	snd.start();

}

p.start = function () {

	this.Ghost_Red.startMove( 26 );

	this.pacMan.startMove( 25 );

	this.gameloop = new Sound ( this.timeline );

	this.gameloop.attachSound ( "snd_ghosts" );

	this.gameloop.start( 0 , 999999999 );

}

p.assignPacMan = function () {

	var pacMan = this.mazeContext.location.attachMovie ( "PacMan" , "PacMan" , ++this.mazeContext.depth );

	pacMan._x = 110;
	pacMan._y = 184;

	pacMan.current_dir = 2;
	pacMan.vx = -2;

	pacMan.engine = this;

	pacMan.animation.stop();

	return pacMan;

};

p.assignGhost = function ( symbolID , x , y ) {

	var ghost = this.mazeContext.location.attachMovie ( symbolID , symbolID , ++this.mazeContext.depth , { _x: x, _y: y, engine: this, pacMan: this.pacMan } );

	ghost.engine = this;

	this.addListener ( ghost );

	ghost.stop();

	return ghost;

}

p.getKeyCode = function () {

	var usercode = 0;

	if ( Key.isDown ( Key.RIGHT ) ) usercode += 1;
	if ( Key.isDown ( Key.LEFT  ) ) usercode += 2;
	if ( Key.isDown ( Key.DOWN  ) ) usercode += 4;
	if ( Key.isDown ( Key.UP    ) ) usercode += 8;

	// avoid opposite direction //

	if ( usercode & 1 && usercode & 2 ) usercode -= 3;
	if ( usercode & 4 && usercode & 8 ) usercode -= 12;

	return usercode;

}

p.switchToPelletMode = function () {

	this.gameloop.stop();

	this.gameloop.attachSound( "snd_pellet" );

	this.gameloop.start( 0 , 999999999 );

	this.broadcastMessage ( "switchToPelletMode" );

	clearInterval( this.pelletTimeout );

	this.pelletTimeout = setInterval ( this , "switchToNormalMode" , 6000 );

}

p.switchToNormalMode = function ( init ) {

	this.gameloop.stop();

	this.gameloop.attachSound( "snd_ghosts" );

	this.gameloop.start( 0 , 999999999 );

	clearInterval( this.pelletTimeout );

	this.broadcastMessage ( "switchToNormalMode" , true );

}

p.addScore = function ( score ) {

	this.score += score;

	this.updateScore();

}